<?php

namespace KukePay\Tencent\Payment\Notify;

use KukePay\Tencent\Payment\Kernel\ConfigFactory;

/**
 * 微信支付回调
 * @package KukePay\Tencent\Native
 */
class Factory extends \KukePay\Kernel\Factory
{
    private $config;
    /**
     * @var array
     */
    private $body;
    /**
     * Factory constructor.
     * @param ConfigFactory $config
     */
    public function __construct(ConfigFactory $config)
    {
        $this->config = $config;
        parent::__construct();
    }

    /**
     * 因为swoole的request每个框架不同 请在外面获取完成xml以后传入即可
     * @param $xml
     * @return $this
     */
    public function setBody($xml)
    {
        $xmlObj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $xmlObj = json_decode(json_encode($xmlObj),true);
        $this->body = $xmlObj;
        return $this;
    }

    /**
     * 获取转换好的数据
     * @return array
     */
    public function getContent()
    {
        return $this->body;
    }

    /**
     * 回调验签处理
     * @param callable $function
     * @return mixed
     */
    public function handlePaidNotify(callable $function)
    {
        $message = $this->getContent();

        foreach( $message as $k=>$v) {
            if($k == 'sign') {
                $xmlSign = $message[$k];
                unset($message[$k]);
            };
        }

        $sign = http_build_query($message);
        //md5处理
        $sign = md5($sign.'&key='.$this->config->getKey());
        //转大写
        $sign = strtoupper($sign);
        //验签通过
        if ( $sign === $xmlSign) {
            return $function($message);
        }
        return $function(false);
    }
}